package cn.ad.server.job.adapter.persistence.job;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import cn.ad.server.common.utils.Constants;
import cn.ad.server.persistence.dao.AdMaterialDao;
import cn.ad.server.persistence.dao.AdSizeDao;
import cn.ad.server.domain.ad.AdMaterial;
import cn.ad.server.domain.ad.AdMaterialGroup;
import cn.ad.server.domain.ad.AdSize;
import cn.ad.server.domain.ad.AdTemplate;
import cn.ad.server.domain.ad.AdTemplateSpec;
import cn.ad.server.domain.ad.Creative;
import cn.ad.server.job.domain.job.AdMaterialRepositoryService;

@Repository
public class AdMaterialRepositoryServant implements AdMaterialRepositoryService {

	static final Logger logger = LoggerFactory.getLogger(AdMaterialRepositoryServant.class);

	@Autowired
	private AdMaterialDao adMaterialDao;

	@Autowired
	private AdSizeDao adSizeDao;

	@Resource(name = "cacheRedisTemplate")
	private RedisTemplate<String, String> redisTemplate;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, Creative> creativeValueOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, AdMaterial> adMaterialsValueOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, AdMaterialGroup> adMaterialGroupValueOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, List<Integer>> mappingValueOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, AdTemplate> adTemplateOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, AdTemplateSpec> adTemplateSpecOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, String> stringValueOperations;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, Long> countOperations;

	private boolean doneFirstScheduled=false;
	
	@Override
	public void warmUpAdMaterials() {

		
		List<AdMaterial> ams;
		String warmUpTime = stringValueOperations.get(Constants.WARM_UP_TIME);
		
		if (!doneFirstScheduled||StringUtils.isEmpty(warmUpTime)) {
			doneFirstScheduled=true;
			ams = adMaterialDao.findAll();
		} else {
			ams = adMaterialDao.findAfterTime(getQueryTime(warmUpTime));//
		}
		
		if (CollectionUtils.isEmpty(ams))
			return;
		for (AdMaterial am : ams) {
			try {
				if (am.getStatus() == 1) {
					//am = attachAdSize(am);//已经表关联查询了。可以去掉。
					if (am != null) {
						adMaterialsValueOperations.set(am.toCacheKey(), am);
					}
				} else if (am.getStatus() != 1) {
					redisTemplate.delete(am.toCacheKey());
				}
			} catch (Exception e) {
				if (am != null) {
					logger.error("错误：在获取AdMaterial_id =" + am.getId() + "数据时发生错误 \n 错误信息：", e);
				}
			}
		}
	}

	public final static int STATUS_VALID = 1;
	
	private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 生成查询时间。
	 * @param warmUpTime
	 * @return
	 */
	public String getQueryTime(String warmUpTime){
		//System.out.println("warmUpTime  ："+ warmUpTime);
		Date date;
		try {
			date = dateFormat.parse(warmUpTime);
		} catch (ParseException e) {
			date = new Date(System.currentTimeMillis()-1000*60*60);//如果失败 ,当前时间往前推1hour
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, -1);
		String queryTime = dateFormat.format(calendar.getTime());
		//System.out.println("queryTime  ："+ queryTime);
		return queryTime;
	}

	/**
	 *
	 * @param adMaterial
	 * @return
	 */
	private AdMaterial attachAdSize(AdMaterial adMaterial) {
		if (adMaterial == null) {
			return null;
		}
		// adSize
		AdSize adSize = adMaterial.getAdSize();
		if (adSize != null) {
			adSize = adSizeDao.selectById(adMaterial.getAdSize().getId(), STATUS_VALID);
			adMaterial.setAdSize(adSize);
		}
		return adMaterial;
	}


}
